package com.jml.spring.resolver;

import com.jml.spring.factory.BeanFactory;
import com.jml.spring.handler.IntegerTypeHandler;
import com.jml.spring.handler.StringTypeHandler;
import com.jml.spring.handler.TypeHandler;
import com.jml.spring.model.RuntimeBeanReference;
import com.jml.spring.model.TypedStringValue;

import java.util.ArrayList;
import java.util.List;

public class BeanDefinitionValueResolver {
    private BeanFactory beanFactory;

    // 策略集合
    private List<TypeHandler> typeHandlers = new ArrayList<>();

    public BeanDefinitionValueResolver(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
        initTypeHandlers();
    }

    private void initTypeHandlers() {
        typeHandlers.add(new IntegerTypeHandler());
        typeHandlers.add(new StringTypeHandler());
        // TODO 思考是否可以将TypeHandler实现类放入配置文件或者配置类中进行灵活配置
    }

    public Object resoleValue(Object value) {
        //引用类型
        if (value instanceof RuntimeBeanReference){
            RuntimeBeanReference reference = (RuntimeBeanReference) value;
            String name = reference.getRef();
            // TODO 此处会发生循环依赖问题
            return beanFactory.getBean(name);
        //基本数据类型
        }else if (value instanceof TypedStringValue){
            TypedStringValue typedStringValue = (TypedStringValue) value;
            String stringValue = typedStringValue.getValue();
            Class targetType = typedStringValue.getTargetType();
            if (targetType != null){
                //TODO 使用策略模式优化
                TypeHandler typeHandler = getTypeHandler(targetType);
                return typeHandler.handleType(stringValue);
            }
            return stringValue;
        }
        // ......
        return null;
    }

    private TypeHandler getTypeHandler(Class targetType) {
        for (TypeHandler handler : typeHandlers) {
            if (handler.supports(targetType)){
                return handler;
            }
        }
        return null;
    }

}
